package com.rongcheng.fortestlist;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * @author frc
 *         created at 16-12-13.
 */

public class SimplePaddingDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint;
    private Context mContext;
    private int mDividerHeight;
    private int mDividerColor;
    private int mMarginLeft;
    private int mMarginRight;
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    public SimplePaddingDecoration(Context context, int dividerHeight, int dividerColor, int marginLeft, int marginRight) {
        this.mContext = context;
        this.mDividerHeight = dividerHeight;
        this.mDividerColor = dividerColor;
        this.mMarginLeft = marginLeft;
        this.mMarginRight = marginRight;
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        a.recycle();
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(mContext.getResources().getColor(dividerColor));
        mPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.bottom = mDividerHeight;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int left = parent.getPaddingLeft() + Utils.dp2px(mContext, mMarginLeft);
        int right = parent.getMeasuredWidth() - parent.getPaddingRight() - Utils.dp2px(mContext, mMarginRight);
        int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + layoutParams.bottomMargin;
            int bottom = top + mDividerHeight;
            if (mPaint != null) {
                c.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }
}
